import 'dart:math';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:gzx_dropdown_menu/gzx_dropdown_menu.dart';
import 'package:ls_work/a_elder/models/elder_entity.dart';

// import 'package:ls_work/a_yyt/models/search_entity.dart';
import 'package:ls_work/mvp/base_page_state.dart';
import 'package:ls_work/a_elder/presenter/elder_content_presenter.dart';
import 'package:ls_work/provider/base_list_provider.dart';
import 'package:ls_work/widgets/my_refresh_list.dart';
import 'package:ls_work/widgets/state_layout.dart';
import 'package:provider/provider.dart';
import 'package:ls_work/a_elder/widget/elder_cell.dart';

import '../../a_yyt/models/floor_list_entity.dart';
import '../../model/building_model.dart';
import '../../res/colors.dart';
import '../../util/toast.dart';
import '../../widgets/drop_item_widget.dart';

class ElderContentPage extends StatefulWidget {
  final int? type;
  final bool? isSelected; //健康登记选择老者
  final Function(ElderInfo elderInfo)? cellClickBlocks;
  final Function(int elderCount)? elderCountBlock;

  ElderContentPage({
    this.type,
    this.isSelected = false,
    this.cellClickBlocks,
    this.elderCountBlock,
  });

  @override
  ElderContentPageState createState() => ElderContentPageState();
}

class ElderContentPageState
    extends BasePageState<ElderContentPage, ElderContentPresenter>
    with AutomaticKeepAliveClientMixin {
  BaseListProvider<ElderInfo> provider = BaseListProvider<ElderInfo>();

  String _keyword = '1';
  int _page = 1;

  var buildingModel = BuildingModel();

  GZXDropdownMenuController _dropdownMenuController =
      GZXDropdownMenuController();

  GlobalKey _stackKey = GlobalKey();

  List<FloorEntity> buildingList = [];
  FloorEntity? selectBuilding;
  List<FloorInfo> floorList = [];
  FloorInfo? selectFloor;


  String customerNameOrBedNoLike = "";

  @override
  bool get wantKeepAlive => true;

  Future<void> _getBuildingData() async {
    try {
      var list = await buildingModel.getBuildingList();
      setState(() {
        buildingList = list;
        selectBuilding = list[0];
        selectBuilding?.iSelected = true;
        setFloor();
      });
      _fectData();
    } catch (e) {
      Toast.show(NetErrorUtils.getNetError(e));
    }
  }

  void setFloor() {
    if (selectBuilding != null) {
      floorList = selectBuilding?.floorList??[];
      if(floorList.first.floorNo=="全部"){
        var first = floorList.first;
        first.iSelected = true;
        selectFloor = first;
      }else{
        var first = FloorInfo(
          floorNo: "全部",
        );
        first.iSelected = true;
        floorList.insert(0, first);
        selectFloor = first;
      }
    }
  }

  @override
  void initState() {
    /// 默认为加载中状态
    provider.setStateType(StateType.empty);
    _page = 1;

    print(presenter);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      /// 接口请求
      _getBuildingData();
    });
    super.initState();
  }

  Future<void> _fectData() async {
    await presenter.fectData(
        _keyword, _page, widget.type!, selectBuilding?.iId??"", selectFloor?.iId??"",customerNameOrBedNoLike);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return widget.isSelected == false
        ? ChangeNotifierProvider<BaseListProvider<ElderInfo>>(
            create: (_) => provider,
            child: Consumer<BaseListProvider<ElderInfo>>(
                builder: (_, provider, __) {
              return DeerListView(
                key: Key('follow_warning_list'),
                itemCount: provider.list.length,
                stateType: provider.stateType,
                onRefresh: _onRefresh,
                loadMore: _loadMore,
                hasMore: provider.hasMore,
                itemBuilder: (_, index) {
                  return ElderCell(
                    isSelected: true,
                    info: provider.list[index],
                  );
                },
              );
            }),
          )
        : Scaffold(
            appBar: AppBar(
              title: Text('选择老人'),
              elevation: 0.5,
            ),
            body: ChangeNotifierProvider<BaseListProvider<ElderInfo>>(
              create: (_) => provider,
              child: Consumer<BaseListProvider<ElderInfo>>(
                  builder: (_, provider, __) {
                return Stack(
                  key: _stackKey,
                  children: [
                    Column(
                      children: [
                        Row(
                          children: [
                            GZXDropDownHeader(
                              // 下拉的头部项，目前每一项，只能自定义显示的文字、图标、图标大小修改
                              items: [
                                GZXDropDownHeaderItem(
                                    selectBuilding?.buildingNo ?? "全部"),
                                GZXDropDownHeaderItem(
                                    selectFloor?.floorNo ?? "全部"),
                              ],
                              // GZXDropDownHeader对应第一父级Stack的key
                              stackKey: _stackKey,
                              // controller用于控制menu的显示或隐藏
                              controller: _dropdownMenuController,
                              borderWidth: 0,
                              dividerHeight: 20,
                              color: Colors.transparent,
                              dividerColor: Colours.order_line,
                              style: TextStyle(
                                  color: Color(0xFF666666), fontSize: 14),
                              dropDownStyle: TextStyle(
                                fontSize: 14,
                                color: Colours.app_main,
                              ),
                              iconDropDownColor: Colours.app_main,
                            )
                                .addToContainer(
                                    padding: EdgeInsets.only(top: 8),
                                    decoration: BoxDecoration(
                                        color: Color(0xfff1f1f1),
                                        borderRadius: 10.borderRadius))
                                .setWeight(3),
                            Container(width: 30,),
                            Row(
                              children: [
                                CommonInput(
                                  hintText: '输入名字/房间搜索',
                                  isDense: true,
                                  padding: EdgeInsets.zero,
                                  border: InputBorder.none,
                                  textInputAction: TextInputAction.search,
                                  maxLines: 1,
                                  onChanged: (str){
                                    customerNameOrBedNoLike = str;
                                  },
                                  onSubmitted: (str){
                                    _onRefresh();
                                  },
                                ).setWeight(1),
                                Icon(Icons.search).onTap(() {
                                  _onRefresh();
                                })
                              ],
                            )
                                .addToContainer(
                                    decoration: BoxDecoration(
                                        color: Color(0xfff1f1f1),
                                        borderRadius: 10.borderRadius),
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 16, vertical: 10))
                                .setWeight(2)
                          ],
                        ).addToContainer(
                            margin: EdgeInsets.symmetric(
                                horizontal: 16, vertical: 8)),
                        DeerListView(
                          key: Key('follow_warning_list'),
                          itemCount: provider.list.length,
                          stateType: provider.stateType,
                          onRefresh: _onRefresh,
                          loadMore: _loadMore,
                          hasMore: provider.hasMore,
                          itemBuilder: (_, index) {
                            return ElderCell(
                              info: provider.list[index],
                              isSelected: widget.isSelected==true,
                              cellClickBlock: (info) {
                                print('🍑' * 10);
                                print(info.name);
                                if(widget.cellClickBlocks!=null){
                                  widget.cellClickBlocks!(info);
                                }
                                Navigator.pop(context);
                              },
                            );
                          },
                        ).setWeight(1)
                      ],
                    ),

                    // 下拉菜单
                    GZXDropDownMenu(
                      // controller用于控制menu的显示或隐藏
                      controller: _dropdownMenuController,
                      // 下拉菜单显示或隐藏动画时长
                      animationMilliseconds: 300,
                      dropdownMenuChanging: (isShow, index) {},
                      dropdownMenuChanged: (isShow, index) {},
                      menus: [
                        GZXDropdownMenuBuilder(
                          dropDownHeight: min(40.0 * buildingList.length,
                              MediaQuery.of(context).size.height * 0.75),
                          dropDownWidget:
                              buildConditionListWidget(buildingList, (data) {
                            _dropdownMenuController.hide();
                            setState(() {
                              selectBuilding = data as FloorEntity?;
                              setFloor();
                            });
                            _onRefresh();
                          }),
                        ),
                        GZXDropdownMenuBuilder(
                          dropDownHeight: min(40.0 * floorList.length,
                              MediaQuery.of(context).size.height * 0.75),
                          dropDownWidget:
                              buildConditionListWidget(floorList, (value) {
                            _dropdownMenuController.hide();
                            setState(() {
                              selectFloor = value as FloorInfo?;
                            });
                            _onRefresh();
                          }),
                        ),
                      ],
                    ),
                  ],
                );
              }),
            ),
          );
  }

  Future _onRefresh() async {
    _page = 1;
    await _fectData();
  }

  Future _loadMore() async {
    _page++;
    await _fectData();
  }

  @override
  ElderContentPresenter createPresenter() {
    return ElderContentPresenter();
  }
}
